<template>
  <view class="customer-invite-container">
    <!-- 顶部导航 -->
    <!-- <view class="header">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon-left-black.png"></image>
      </view>
      <view class="title">让他客户加我</view>
    </view> -->

    <!-- 主要内容 -->
    <view class="content">
      <!-- 邀约话术选择 -->
      <view class="invite-section">
        <view class="section-title-h2">发送邀请，让客户主动加我</view>
        <view class="section-title">邀约话术</view>
        <view class="invite-list">
          <view 
            v-for="(item, index) in inviteScripts" 
            :key="index" 
            class="invite-item" 
            :class="{ active: selectedScript === index }"
            @click="selectScript(index)"
          >
            <view class="item-content">{{item.word}}</view>
            <view class="check-icon">
              <view class="check-circle"></view>
            </view>
          </view>
        </view>
        <view class="custom-invite" @click="is_label_search_popup = true">
          <!-- <view class="custom-title">让{{mer_storeType || 'xx行业'}}客户加我</view> -->
          <view class="custom-title">让{{mer_storeType || 'xx行业'}}客户加我</view>
          <view class="custom-arrow">
            <view class="arrow-right">></view>
          </view>
        </view>
      </view>

      <!-- 选择邀约客户数量 -->
      <view class="customer-count-section">
        <view class="section-title-h2">选择邀约客户数量</view>
        <view class="tip-text">
          <view class="tip-text-item">邀约推送后，主动添加您的数量，由被邀约客户决定。</view>
          <view class="tip-text-item">在个人中心页面，点击"我的推广"查看已邀约记录</view>
        </view>
        <view class="count-list">
          <view 
            v-for="(item, index) in customerCounts" 
            :key="index" 
            class="count-item"
            :class="{ active: selectedCount === index }"
            @click="selectCount(index)"
          >
            <view class="count-text">{{item.customer_count}}</view>
            <view class="price-text">{{item.price}}元</view>
            <view class="check-circle"></view>
          </view>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="bottom-btn" @click="submitInvite">邀约</view>
    </view>

    
    <!-- 行业标签弹窗 -->
    <labelSearchListPopup 
      :setLabelList="setLabelList" 
      :multiIndex="multiIndex" 
      :is_label_search_popup='is_label_search_popup' 
      @closeLabelSearchPopup="closeLabelSearchPopup" 
      @changeMultiIndex="changeMultiIndex" 
      @selectLabelSearchPopup="selectLabelSearchPopup">
    </labelSearchListPopup>
  </view>
</template>

<script>
import { getSystemGroupData, getLabelList, inviteCreate } from '@/api/api.js';
import labelSearchListPopup from '@/components/labelSearchListPopup/index.vue';

export default {
  components: {
    labelSearchListPopup
  },
  data() {
    return {
      inviteScripts: [],
      selectedScript: 0, // 默认选中第三个
      customerCounts: [],
      selectedCount: 0, // 默认选中第二个
      loading: false,
      
      // 行业标签相关数据
      is_label_search_popup: false,
      setLabelList: [],
      multiArray: [],
      labelList: [],
      multiIndex: [0, 0],
      mer_storeType: '',
      formData: {
        label_id: 0,
        label_id2: 0
      }
    }
  },
  onLoad(options) {
    // 确保页面被正确加载
    console.log('customer_invite page loaded', options);
    this.getCustomerCounts();
    this.getInviteScripts();
    this.getLabel();
  },
  onShow() {
    // 确保页面显示时有依赖关系
    console.log('customer_invite page shown');
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    selectScript(index) {
      this.selectedScript = index;
    },
    selectCount(index) {
      this.selectedCount = index;
    },
    getCustomerCounts() {
      this.loading = true;
      getSystemGroupData({name: 'customer_count'}).then(res => {
        if(res.status === 200 && res.data.list) {
          this.customerCounts = res.data.list;
        }
        this.loading = false;
      }).catch(err => {
        console.log('获取数据失败', err);
        this.loading = false;
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      });
    },
    getInviteScripts() {
      this.loading = true;
      getSystemGroupData({name: 'invite_script'}).then(res => {
        if(res.status === 200 && res.data.list) {
          this.inviteScripts = res.data.list;
        }
        this.loading = false;
      }).catch(err => {
        console.log('获取数据失败', err);
        this.loading = false;
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      });
    },
    submitInvite() {
      if(!this.customerCounts.length) {
        return uni.showToast({
          title: '请等待数据加载',
          icon: 'none'
        });
      }
      
      if(!this.formData.label_id) {
        return uni.showToast({
          title: '请选择行业',
          icon: 'none'
        });
      }
      
      const selectedCountData = this.customerCounts[this.selectedCount];
      const selectedScriptData = this.inviteScripts[this.selectedScript];
      
      // uni.showModal({
      //   title: '确认邀约',
      //   content: `您选择了${selectedCountData.customer_count}位客户，需支付${selectedCountData.price}元，确认邀约吗？`,
      //   success: (res) => {
      //     if(res.confirm) {
      //       // 这里添加支付逻辑
      //       uni.showToast({
      //         title: '邀约成功',
      //         icon: 'success'
      //       });
      //     }
      //   }
      // });

      const params = {
        "title":this.inviteScripts[this.selectedScript].word,
        "label_id":this.formData.label_id,
        "label_id2":this.formData.label_id2,
        "customer_count_id":this.selectedCount+1,
        "recharge":"routine"
      }
      inviteCreate(params).then(res => {
        if(res.status === 200) {
          const {timestamp, nonceStr, package:packageValue, signType, paySign} = res.data.result.config;
          uni.showToast({
            title: '邀约成功',
            icon: 'success'
          });
          // 唤起微信支付
          uni.requestPayment({
            timeStamp: timestamp,
            nonceStr: nonceStr,
            package: packageValue,
            signType: signType,
            paySign: paySign,
          }).then(res => {
            console.log('res-支付回调', res);
            const targetItem = res[1]; 
            if (targetItem && targetItem.errMsg === 'requestPayment:ok') { 
              uni.showToast({
                title: '邀约成功',
                icon: 'success'
              });
              // 返回首页
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                });
              }, 1000);
            } else {
              uni.showToast({ 
                title: '支付失败',
                icon: 'none'
              });
              // 刷新页面
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/customer_invite/index'
                });
              }, 1000);
            }
          }).catch(err => {
            console.log('err', err);
          });
        }
        this.loading = false;
      }).catch(err => {
        console.log('获取数据失败', err);
        this.loading = false;
        uni.showToast({
          title: err,
          icon: 'none'
        });
        // 跳转到登录页面
        if(err === '去登录') {
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/user/index'
            });
          }, 1000);
        }
      });
    },
    
    // 以下是行业标签相关方法
    /**
     * 获取行业列表
     */
    getLabel() {
      let that = this,
        customerIndustry = this.$Cache.get('customerIndustry'),
        engagedIndustry = this.$Cache.get('engagedIndustry'),
        is_sort = true;
      getLabelList({customerIndustry, engagedIndustry, is_sort, is_customer_industry: true}).then(res=>{
        that.labelList = res.data.list;
        that.setLabelList = res.data.list;
        that.multiArray = [res.data.list, res.data.list[that.multiIndex[0]].children || []];
        that.$set(that, 'multiArray', that.multiArray);
      }).catch(err=>{
        console.log('err', err);
      });
    },
    // 关闭搜索标签
    closeLabelSearchPopup() {
      this.is_label_search_popup = false;
      this.mer_storeType = this.setLabelList[this.multiIndex[0]].label_name + 
        (this.setLabelList[this.multiIndex[0]].children ? 
        '-' + this.setLabelList[this.multiIndex[0]].children[this.multiIndex[1]].label_name : '');
      
      this.formData.label_id = this.setLabelList[this.multiIndex[0]].label_id;
      this.formData.label_id2 = this.setLabelList[this.multiIndex[0]].children ? 
        this.setLabelList[this.multiIndex[0]].children[this.multiIndex[1]].label_id : 0;
    },
    // 选择便签发送改变时触发
    changeMultiIndex(multiIndex) {
      this.$set(this, 'multiIndex', multiIndex);
    },
    // 搜索标签弹窗
    async selectLabelSearchPopup(keywords) {
      let that = this;
      if(!keywords) {
        that.$set(that, 'setLabelList', that.labelList);
      } else {
        let setLabelList = [];
        that.labelList.forEach((item) => {
          if(item.label_name.includes(keywords)) {
            setLabelList.push(item);
          } else {
            if(item.children && item.children.length) {
              let children = [];
              item.children.forEach((item2) => {
                if(item2.label_name.includes(keywords)) {
                  children.push(item2);
                }
              });
              if(children.length) {
                item.children = children;
                setLabelList.push(item);
              }
            }
          }
        });
        if(setLabelList.length) {
          that.$set(that, 'setLabelList', setLabelList);
        } else {
          return that.$util.Tips({title: '暂无该搜索项'});
        }
      }
      this.$set(this, 'multiIndex', [0,0]);
    }
  }
}
</script>

<style lang="scss" scoped>
.customer-invite-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  height: 90rpx;
  background-color: #FFE103;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: relative;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    image {
      width: 40rpx;
      height: 40rpx;
    }
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #000;
    flex: 1;
    text-align: center;
  }
}

.content {
  flex: 1;
  padding: 30rpx;
  background: #fff;
}

.invite-section, .customer-count-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  // margin-bottom: 30rpx;
  padding-top: 0;
}
.section-title-h2 {
  font-size: 46rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  background: #036803;
  color:#fff;
  padding: 10rpx 20rpx;
  display: inline-block;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
  .tip-text-item {
    position: relative;
    padding-left: 40rpx;
    color: #333;
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 0;
      width: 10rpx;
      height: 10rpx;
      background: #FF4948;
      border-radius: 50%;
    }
  }
}

.invite-list {
  .invite-item {
    // border: 1px solid #eee;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    display: flex;
    align-items: center;
    
    &.active {
      // border-color: #026803;
      // background-color:#d3ecd4;
       
    .check-icon {

      .check-circle {
        border:none;
        background-image: url('https://ly.jukee.net/static/check.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
      }
    }
    }
    
    .item-content {
      flex: 1;
      color: #333;
      font-weight: 600;
    }
    
    .check-icon {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .check-circle {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        border: 1px solid #888888;
      }
    }
  }
}

.custom-invite {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1px solid #dadada;
  margin-top: 50rpx;
  
  .custom-title {
    font-size: 36rpx;
    font-weight: bold;
    background: #036803;
    color:#fff;
    padding: 10rpx 20rpx;
    display: inline-block;
  }
  
  .custom-arrow {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .arrow-right {
      font-size: 100rpx;
      color: #333;
    }
  }
}

.count-list {
  // display: flex;
  // justify-content: space-between;
  
  .count-item {
    width: 100%;
    height: 110rpx;
    border-bottom: 1px solid #dadada;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    &:last-child {
      border-bottom: none;
    }
    &.active {
      // border-color: #FFE103;
      // background-color: #FFFBE6;
      .check-circle {
        border:none;
        background-image: url('https://ly.jukee.net/static/check.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
      }
    }
    
    .count-text {
      font-size: 30rpx;
      font-weight: bold;
    }
    
    .price-text {
      font-size: 30rpx;
      font-weight: bold;
      margin-top: 10rpx;
      margin-left: 280rpx;
      color: #333;
    }
    
    .check-circle {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      // background-color: #026803;
      border: 1px solid #888888;
    }
  }
}

.bottom-btn {
  height: 90rpx;
  background-color: #FFE103;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  font-weight: bold;
  color: #000;
  margin-top: 100rpx;
  max-width: 350rpx;
  margin: 0 auto;
  border-radius: 50rpx;
}
</style> 